 <!-- 编辑商品 -->
 <!-- 商品列表 --创建 -->
<template>
  <div>
    <!-- 商品介绍 -->
    <el-card class="box-card">
      <p>商品(Spu)介绍</p>
      <el-form label-width="110px" :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label="商品名称" prop="title">
          <el-input placeholder="请输入内容" v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="原始价格" prop="price">
          <el-input placeholder="请输入内容" v-model="ruleForm.price">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="originalPrice">
          <el-input placeholder="请输入内容" v-model="ruleForm.originalPrice">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="VIP价格" prop="vipPrice">
          <el-input placeholder="请输入内容" v-model="ruleForm.vipPrice">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="剩余库存" prop="stock">
          <el-input placeholder="请输入内容" v-model="ruleForm.stock" :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="运费模板" prop="freightTemplateId">
          <el-select v-model="ruleForm.freightTemplateId" placeholder="请选择商品运费模板">
            <el-option v-for="item in adStatusMap" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否在售">
          <template>
            <el-radio v-model="ruleForm.status" :label="1">在售</el-radio>
            <el-radio v-model="ruleForm.status" :label="0">下架</el-radio>
          </template>
        </el-form-item>
        <el-form-item prop="imgList" label="商品图片">
          <!-- 图片上传 -->
          <el-upload :headers="headers" action="/upload/admin" :file-list="imgList" list-type="picture-card" :on-success="onSuccess" :before-upload="beforeUpload" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
            <el-icon class="el-icon-plus avatar-uploader-icon ">
            </el-icon>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl">
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <el-input placeholder="单/个/盒" v-model="ruleForm.unit">
          </el-input>
        </el-form-item>
        <el-form-item label="所属类目" prop="categoryId">
          <el-cascader v-model="ruleForm.categoryId" :options="options" :props="defaultParams" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="商品简介" prop="descripiton">
          <el-input placeholder="请输入内容" v-model="ruleForm.descripiton">
          </el-input>
        </el-form-item>
        <el-form-item label="商品详细介绍" prop="detail">
          <rich-text v-model="ruleForm.detail"></rich-text>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 商品参数 -->
    <el-card class="box-card">
      <p>商品参数</p>
      <el-button type="primary" size="medium" style="margin-bottom:10px" @click="parameterAdd">添加</el-button>
      <el-table :data="attributeList" style="width: 100%">
        <el-table-column label="商品参数名称" prop="attribute">
        </el-table-column>
        <el-table-column label="商品参数值" prop="value">
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="medium" @click="attributeList.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 商品参数添加对话框 -->
    <el-dialog title="设置商品参数" :visible.sync="dialogFormVisible">
      <el-form :model="attrFrom" :rules="attrrules" ref="attrFrom" label-width="110px" class="demo-ruleForm">
        <el-form-item label="商品参数名称" prop="attribute">
          <el-input v-model="attrFrom.attribute"></el-input>
        </el-form-item>
        <el-form-item label="商品参数值" prop="value">
          <el-input v-model="attrFrom.value"></el-input>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button @click="dialogFormVisible=false"> 取消</el-button>
          <el-button type="primary" @click="hanlderMan('attrFrom')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 规格维度 -->
    <el-card class="box-card">
      <p>规格维度</p>
      <el-button type="primary" size="medium" style="margin-bottom:20px" @click="vdoingAdd">添加</el-button>
      <el-table :data="specificationList" style="width: 100%">
        <el-table-column label="维度ID" prop="id">
        </el-table-column>
        <el-table-column label="维度名称" prop="title">
        </el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate">
          <template slot-scope="scope">
            {{new Date (scope.row.gmtCreate).format()}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="medium" @click="handleEdit(scope.row,scope.$index)">修改</el-button>
            <el-button type="danger" size="medium" @click="specificationList.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 规格维度添加对话框 -->
    <el-dialog :title="title1" :visible.sync="dialogTableVisible">
      <el-form :model="titleForm" :rules="titlerules" ref="titleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="类型名称" prop="title">
          <el-input v-model="titleForm.title"></el-input>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button @click="dialogTableVisible=false"> 取消</el-button>
          <el-button type="primary" @click="hanlderRit('titleForm')">{{title1=="创建商品参数"?'确认创建':'确认修改'}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 商品(sku)详情 -->
    <el-card class="box-card">
      <p>商品(sku)详情</p>
      <el-button type="primary" size="medium" style="margin-bottom:20px" @click="detailAdd">批量定价</el-button>
      <div class="box_tag">
        <p v-for="(items,index) in specificationList" :key="index">
          <el-tag :disable-transitions="false" type="warning">
            {{items.title}}
          </el-tag>
          <el-tag v-for="(item1,indexs) in items.values" :key="indexs" closable :disable-transitions="false" @close="handleClose(items,item1)">
            {{item1}}
          </el-tag>
          <el-input v-if="items.inputVisible" v-model="items.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm(index)">
          </el-input>
          <el-button v-else size="small" @click="handInput(index)">+ 添加</el-button>
        </p>
      </div>
      <el-table :data="skuList" :span-method="combineSpan" style="width: 100%" border>
        <el-table-column v-for="(item,index) in specificationList" :label="item.title" :key="index" :prop="'id_'+item.title" align="center">
        </el-table-column>
        <el-table-column label="SkuId" align="center">
        </el-table-column>
        <el-table-column label="￥价格(元)" prop="price" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.price" :min="0" size="mini"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="￥VIP价(元)" prop="vipPrice" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.vipPrice" :min="0" size="mini"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="￥吊牌价(元)" prop="originalPrice" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.originalPrice" :min="0" size="mini"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="库存(件)" prop="stock" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.stock" :min="0" size="mini"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="重量(克)" prop="weight" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.weight" :min="0" size="mini"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="sku图片" prop="img" align="center">
          <template #default="scope">
            <div @click="imgIndex=scope.$index">
              <el-upload class="avatar-uploader" action="/upload/admin" :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccessImg">
                <img v-if="scope.row.img" :src="scope.row.img" class="avatar" style="width: 100px;height: 100px;" />
                <el-icon v-else class="avatar-uploader-icon">
                </el-icon>
              </el-upload>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="条形码" prop="barCode" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.barCode" style="width: 150px;"><template #append>
                <el-button @click="scope.row.barCode=new Date().getTime()" type="primary" size="mini">随机</el-button>
              </template></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 商品详情-批量定价对话框 -->
    <el-dialog title="批量定价" :visible.sync="dialogVisible">
      <el-form :model="priceForm" :rules="pricerule" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="现价(￥)" prop="price">
          <el-input-number v-model="priceForm.price" @change="handleChange" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="VIP价格(￥)" prop="vipPrice">
          <el-input-number v-model="priceForm.vipPrice" @change="handleChange" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="吊牌价(￥)" prop="originalPrice">
          <el-input-number v-model="priceForm.originalPrice" @change="handleChange" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button @click="dialogVisible=false" size="medium"> 取消</el-button>
          <el-button type="primary" @click="hanlderApp" size="medium">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div class="box_button">
      <el-button type="primary" size="medium" @click="padlock"> 关闭</el-button>
      <el-button type="primary" size="medium" @click="dialogVisibleLIst=true">保存商品</el-button>
    </div>
    <!-- 点击保存商品的对话框 -->
    <el-dialog :visible.sync="dialogVisibleLIst" title="提示" width="30%">
      <span>确定要保存商品吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitForm">确认</el-button>
          <el-button type="primary" @click="dialogVisibleLIst=false">返回保存商品</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

</template>
<script>
import cookie from "js-cookie";
import Apiadmin from "../../api/admin"
import RichText from "@/components/richtext/RichText.vue"
export default {
  components: { RichText },
  data() {
    return {
      adStatusMap: [ //运费模板
        {
          value: 0,
          name: '广东发包邮'
        }
      ],
      // 上传图片请求头
      headers: {
        AdminToken: cookie.get('AdminToken')
      },
      options: [], //优惠类目数据
      defaultParams: { // 级联选择器的配置
        checkStrictly: true, // 父子节点不互相关联
        label: 'title',  //渲染上去的名字
        value: 'id', //选中时的id
        children: 'childrenList',  //子节点数组
        emitPath: false // 只返回该节点的值
      },
      // 商品介绍表单数据
      ruleForm: {
        title: '',// 商品名称
        price: '0', // 原始价格
        originalPrice: '0',// 当前价格
        vipPrice: '0',// VIP价格
        stock: '',// 剩余库存
        freightTemplateId: '',// 运费模板
        status: 1, // 是否在售
        img: '', // 商品图片
        imgList: [],// 图片
        unit: '',// 商品单位
        categoryId: '',// 所属类目
        descripiton: '',// 商品简介
        detail: '',
      },
      // 商品介绍表单验证
      rules: {
        title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        originalPrice: [{ required: true, message: '请输入原始价格', trigger: 'blur' }, { pattern: /^\d{1,}$/, message: '请输入数字类型', trigger: 'blur' }],
        price: [{ required: true, message: '请输入当前价格', trigger: 'blur' }, { pattern: /^\d{1,}$/, message: '请输入数字类型', trigger: 'blur' }],
        vipPrice: [{ required: true, message: '请输入VIP价格', trigger: 'blur' }, { pattern: /^\d{1,}$/, message: '请输入数字类型', trigger: 'blur' }],
        status: [{ required: true, message: '请选中是否在售', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入商品单位', trigger: 'blur' }],
        detail: [{ required: true, message: '请输入商品详情介绍', trigger: 'blur' }],
      },
      // 商品参数数据
      attributeList: [], //表格数据
      dialogFormVisible: false, //商品参数对话框关闭
      attrFrom: {  //对话框数据
        attribute: '', //商品参数名称
        value: '', //商品参数值
      },
      // 商品参数表单验证
      attrrules: {
        attribute: [{ required: true, message: '请输入商品参数名称', trigger: 'blur' }],
        value: [{ required: true, message: '请输入商品参数值', trigger: 'blur' }],
      },
      // 规格维度数据
      title1: '创建商品参数',
      specificationList: [], //表格数据
      dialogTableVisible: false, //规格维度对话框关闭
      titleForm: {  //对话框数据
        title: null,
      },
      // 规格维度表单验证
      titlerules: {
        title: [{ required: true, message: '请输入商品参数名称', trigger: 'blur' }]
      },
      // 商品详情数据
      dialogVisible: false, //批量定价对话框关闭
      priceForm: {
        price: '0', //现价
        vipPrice: '0', //vip价格
        originalPrice: '0', //吊牌价

      },
      // 商品详情(批量报价表单验证)
      pricerule: {
        price: [{ required: true, message: '请输入现价', trigger: 'blur' }, { pattern: /^\d{1,}$/, message: '请输入数字类型', trigger: 'blur' }],
        vipPrice: [{ required: true, message: '请输入VIP价格', trigger: 'blur' }, { pattern: /^\d{1,}$/, message: '请输入数字类型', trigger: 'blur' }],
        originalPrice: [{ required: true, message: '请输入吊牌价', trigger: 'blur' }, { pattern: /^\d{1,}$/, message: '请输入数字类型', trigger: 'blur' }],
      },
      dialogImageUrl: '', //图片
      dialogVisible: false, //图片
      skuList: [],  //商品(sku)详情表格数据
      imgList: [],
      dialogVisibleLIst: false, //关闭


    }
  },
  computed: {
    createSku() { //笛卡尔计算法
      let list = this.specificationList
      let valueList = list.map(item => item.values).filter(item => item.length > 0);
      // console.log(valueList)
      let titles = list.map((item) => {
        return item.title;
      });
      let sku = valueList.reduce((total, item) => {
        let arr = [];
        total.forEach((a) => {
          item.forEach((b) => {
            arr.push(a.concat([b]));
          });
        });

        return arr;
      },
        [[]]
      );
      let { vipPrice, price, originalPrice } = this.priceForm;
      let arry = sku.map((item) => {
        let obj = {
          title: [],
          originalPrice,
          price,
          vipPrice,
          stock: 0,
          specification: [], //规格维度
          weight: "",
          barCode: "",
          img: "",
        };
        item.forEach((val, index) => {
          let key = "id_" + titles[index];
          obj[key] = val;
          obj.title.push(val);
          obj.specification.push(titles[index] + "_" + val); //插入的是id_颜色与id_尺寸
        })
        obj.title = obj.title.join();
        obj.specification = obj.specification.join();
        return obj;
      })
      if (arry[0].title.length == 0) {
        return [];
      }
      this.skuList = arry
      return arry;
    },

  },
  created() {
    this.productList()
    this.detailList() //商品详情

  },
  watch: {
    $$route(to) {
      if (to.name == 'edit') {
        this.detailList(to)
      }
    }
  },
  methods: {
    //上传图片方法
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    //点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //成功时触发事件
    onSuccess(res) {
      // console.log(res)
      if (res.errno == 200) {
        this.ruleForm.imgList = [res.url];  //上传图片成功的路径
        this.ruleForm.img = res.url
      }
    },
    //选择确定时触发
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/JPEG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      return isLt2M;
    },
    //sku上传头像
    handleAvatarSuccessImg(res) {
      // console.log(res);
      this.skuList[this.imgIndex].img = res.url;
    },
    //请求类目数据 
    productList() {
      Apiadmin.categoryTree().then(res => {
        // console.log(res)
        this.options = res.data

      })
    },
    // 计数器事件
    handleChange(value) {
      console.log(value);
    },
    // 商品参数添加按钮
    parameterAdd() {
      this.dialogFormVisible = true
      this.initObj(this.attrFrom, {})  //清空表单
      this.$nextTick(() => {
        this.resetForm("attrFrom")
      })
    },
    // 商品参数对话框确定按钮
    hanlderMan(attrFrom) {
      this.$refs[attrFrom].validate((valid) => {
        if (valid) {
          this.attributeList.push(this.attrFrom)
          this.dialogFormVisible = false
          this.attrFrom = {}  //清空表单
        } else {
          return false;
        }
      })
    },
    // 规格维度添加按钮
    vdoingAdd() {
      this.title1 = '创建商品参数'
      this.dialogTableVisible = true
      this.initObj(this.titleForm, {}) //清空表单
      this.$nextTick(() => {
        this.resetForm("titleForm")
      })
    },
    // 规格维度修改按钮
    handleEdit(row, index) {
      this.title1 = '修改商品参数'
      this.dialogTableVisible = true
      this.titleForm = JSON.parse(JSON.stringify(row))
    },
    // 规格维度对话框确定按钮
    hanlderRit(titleForm) {
      this.$refs[titleForm].validate((valid) => {
        if (valid) {
          // 添加
          if (this.title1 == "创建商品参数") {
            this.dialogTableVisible = false
            this.specificationList.push({
              title: this.titleForm.title,
              // 将创建开始时间和结束时间转换成时间戳
              gmtCreate: new Date().getTime(),
              gmtUpdate: new Date().getTime(),
              values: [],
              inputVisible: false,
              inputValue: '',
            })
            this.titleForm = {} //清空表单
          }
          // 修改
          if (this.title1 == "修改商品参数") {
            this.dialogTableVisible = false
            this.specificationList.map(item => {
              if (item.gmtCreate == this.titleForm.gmtCreate) {
                return item.title = this.titleForm.title
              }
            })
            this.titleForm = {} //清空表单
          }


        } else {
          return false;
        }
      });
    },
    // 商品详情(批量定价)按钮
    detailAdd() {
      this.dialogVisible = true
    },
    // 商品详情删除tag标签
    handleClose(items, item1) {
      items.values.splice(items.values.indexOf(item1), 1)
      // this.createSku()
    },
    // 商品详情tag标签
    handInput(index) {
      this.specificationList[index].inputVisible = true;
    },
    // 失去焦点
    handleInputConfirm(index) {
      let inputValue = this.specificationList[index].inputValue
      if (inputValue) {
        this.specificationList[index].values.push(inputValue);
      }
      this.specificationList[index].inputVisible = false;
      this.specificationList[index].inputValue = '';
      // this.createSku()
    },
    // 商品详情(批量定价)对话框确定按钮
    hanlderApp() {
      this.dialogVisible = false
    },
    // 关闭按钮
    padlock() {
      this.$router.push("/index/shoppmanage/product")  //跳转到商品列表页面
    },
    // 商品详情
    detailList() {
      // console.log(this.$route.params.id)
      // 路由传过来的id
      let spuId = this.$route.params.id
      this.imgList = []
      Apiadmin.productDetail(spuId).then(res => {
        // console.log(res)
        let { errno, data, errmsg } = res
        let { specificationList, skuList, attributeList, imgList } = data
        if (errno == 200) {
          this.ruleForm = data  //表格数据
          imgList.map(item => { // 商品图片渲染
            this.imgList.push({ url: item })
          })
          this.attributeList = attributeList
          specificationList.forEach(item => item.values = [])//添加一个空的values数组
          skuList.forEach(sku => {
            // 将数组转换成字符串规格
            specificationList = sku.specification.split(',').map(item => item.split('_')[0]).map(item => specificationList.find(item2 => item2.title == item))
            let titles = sku.title.split(',') // 拿到每个valued的title值 转换成数组
            specificationList.forEach((spe, index) => {
              let key = "id_" + spe.title
              sku[key] = titles[index]
              if (spe.values.indexOf(titles[index]) == -1) {
                spe.values.push(titles[index])
              }
            })
          })
          this.specificationList = specificationList
          this.skuList = skuList
        } else {
          this.$message({
            message: errmsg,
            type: 'error'
          });
        }
      })
    },
    // 表格跨行
    combineSpan({ row, column, rowIndex, columnIndex }) {
      let rowspan = this.skuList.length / this.specificationList[0].values.length
      for (let index = 0; index < this.specificationList.length; index++) {
        if (index !== 0) {
          rowspan = rowspan / this.specificationList[index].values.length
        }
        if (columnIndex === index) {
          if (rowIndex % rowspan === 0) {
            return {
              rowspan: rowspan,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      }
    },
    //修改保存商品
    submitForm() {
      // console.log(this.ruleForm)
      // console.log(this.priceForm)
      // vip价格vipPrice <= 原始价格price <= 当前价格originalPrice
      // vip价格vipPrice <= 现价price <= 吊牌价originalPrice
      let ruleForm = this.ruleForm
      let priceForm = this.priceForm
      if (parseInt(ruleForm.originalPrice) < parseInt(ruleForm.price) || parseInt(ruleForm.originalPrice) < parseInt(ruleForm.vipPrice) || parseInt(ruleForm.price) < parseInt(ruleForm.vipPrice)) {
        this.$message({
          message: '必须 vip价格 <= 现价 <= 原价',
          type: 'error'
        });
        return
      }
      if (parseInt(priceForm.originalPrice) < parseInt(priceForm.price) || parseInt(priceForm.originalPrice) < parseInt(priceForm.vipPrice) || parseInt(priceForm.price) < parseInt(priceForm.vipPrice)) {
        this.$message({
          message: '必须 vip价格 <= 现价 <= 原价',
          type: 'error'
        });
        return
      }
      this.dialogVisibleLIst = true
      this.ruleForm.img = this.ruleForm.imgList[0]
      let spuDTO = { ...this.ruleForm, specificationList: this.specificationList, attributeList: this.attributeList, skuList: [...this.skuList] }
      Apiadmin.productEdit(JSON.stringify(spuDTO)).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          // console.log(res)
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.dialogVisibleLIst = false
          this.$router.push({ name: 'product' }) //返回商品列表页面
        } else {
          this.$message({
            message: "修改失败",
            type: 'error'
          });
        }
      })
    },
    //去除表单验证
    resetForm(formName) {
      //clearValidate方法为移除表单的校验结果          
      this.$refs[formName].clearValidate();
    },

  }
}
</script>
<style scoped  lang="less">
.text {
  font-size: 14px;
}
p {
  font-weight: 700;
}
.item {
  padding: 18px 0;
}
.el-form {
  margin-left: 60px;
}
.box_button {
  margin-top: 20px;
  text-align: right;
}
.box_tag .el-tag {
  margin-right: 10px;
}
.box_tag .el-input {
  width: 90px;
  margin-bottom: 2px;
  vertical-align: bottom;
}
</style>